<template>
  <div class="settings-container">
    <div class="app-container">
      <el-card>
        <el-tabs v-model="activeName">
          <!-- 左侧 -->
          <el-tab-pane label="角色管理" name="role">
            <!-- 按钮 -->
            <el-button
              icon="el-icon-plus"
              size="small"
              type="primary"
              @click="showTanCeng"
              >新增角色</el-button
            >

            <!-- 表格 -->
            <!-- :data:数据源（对象数组） -->
            <el-table :data="roleList">
              <el-table-column
                label="序号"
                width="100"
                type="index"
                :index="indexMethod"
              />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作" #default="{ row }">
                <el-button
                  size="small"
                  type="success"
                  @click="handleOpenAssignDialog(row.id)"
                  >分配权限</el-button
                >
                <el-button
                  size="small"
                  type="primary"
                  @click="handleOpenEditDialog(row.id)"
                  >编辑</el-button
                >
                <el-button size="small" type="danger" @click="handleDel(row.id)"
                  >删除</el-button
                >
              </el-table-column>
            </el-table>
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="query.page"
              :page-sizes="[2, 3, 5, 10]"
              :page-size="query.pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
            >
            </el-pagination>
          </el-tab-pane>

          <el-tab-pane label="公司信息" name="company">
            <el-alert title="不行改奥，给你开除喽" type="info"> </el-alert>
            <!-- 表单 -->
            <el-form label-width="80px" v-model="companyForm">
              <el-form-item label="公司名称">
                <el-input
                  style="width: 50%"
                  v-model="companyForm.name"
                  disabled
                ></el-input>
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input
                  v-model="companyForm.companyAddress"
                  disabled
                ></el-input>
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyForm.mailbox" disabled></el-input>
              </el-form-item>
              <el-form-item label="介绍">
                <el-input
                  type="textarea"
                  v-model="companyForm.remarks"
                  disabled
                ></el-input>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 新增角色 -->
      <el-dialog
        title="又来加人了奥？"
        :visible="showDialog"
        @close="closeDialog"
      >
        <el-form ref="roleForm" :model="form" label-width="80px">
          <el-form-item label="角色名称">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="form.description"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="addFormSubmit">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑角色 -->
      <el-dialog
        title="这次是干嘛"
        :visible="showEditDialog"
        @close="handleEditClose"
      >
        <el-form ref="roleForm" :model="form" label-width="80px">
          <el-form-item label="角色名称">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="form.description"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleEditClose">取 消</el-button>
          <el-button type="primary" @click="handleEdit">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配权限 -->
      <el-dialog
        title="分配权限"
        :visible="showAssignDialog"
        @close="handleAssignClose"
      >
        <!-- 权限树形组件 -->
        <!-- 设置获取tree组件选中的节点有两种方式 -->
        <!-- 1、通过node（节点对象）方式 2、通过key的方式  需要给tree添加node-key属性 -->

        <!-- 代码中可以通过this.$refs.treeRef获取到tree组件对象、调取方法 -->
        <!-- 1、获取：getCheckedNodes（） / getCheckedKeys（） -->
        <!-- 2、设置：setCheckedNodes（【】） / getCheckedKeys（【permIds】） -->
        <el-tree
          :data="permTreeData"
          :props="{ label: 'name' }"
          show-checkbox
          default-expand-all
          check-strictly
          node-key="id"
          ref="treeRef"
        >
        </el-tree>
        <template #footer>
          <el-button @click="handleAssignClose">取消</el-button>
          <el-button type="primary" @click="handleAssign">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getPermListAPI } from "@/api/permissions";
import { list2Tree } from "@/utils/shift";
import {
  getUerRoleAPI,
  AddRoleAPI,
  delRoleAPI,
  getRoleDetailAPI,
  editRoleAPI,
  getCompanyDetailAPI,
  assignPermAPI,
} from "@/api/setting";
export default {
  name: "SettingsView",
  data() {
    return {
      currentPage4: 1,
      // 收集激活的任务栏
      activeName: "role",
      //角色信息
      roleList: [],
      query: {
        page: 1,
        pagesize: 5,
      },
      total: 0,
      //控制弹层
      showDialog: false,
      //添加角色列表
      showEditDialog: false,
      // 分配弹窗
      showAssignDialog: false,

      form: {
        name: "",
        description: "",
      },
      companyForm: {
        name: "",
        companyAddress: "",
        remarks: "",
        mailbox: "",
      },
      // 树形权限
      permTreeData: [],
    };
  },
  watch: {
    async activeName(newVal) {
      if (newVal !== "company") return;
      // 如果获取过  直接结束
      if (this.companyForm.id) return;
      //发请求获取详情
      const resp = await getCompanyDetailAPI(
        this.$store.state.user.userInfo.companyId
      );
      // 做回显
      this.companyForm = resp.data;
    },
  },
  created() {
    this.getRole();
  },
  methods: {
    //获取角色列表
    async getRole() {
      //掉接口发请求
      const { data } = await getUerRoleAPI(this.query);
      const { rows, total } = data;
      (this.total = total), (this.roleList = rows);
    },
    //关闭弹层，清空表单
    closeDialog() {
      this.form = {};
      this.showDialog = false;
      this.$refs.roleForm.resetFields();
      // 遍历数组
    },
    //弹层展示
    showTanCeng() {
      this.showDialog = true;
    },
    //掉接口发请求
    addFormSubmit() {
      this.$refs.roleForm.validate(async () => {
        await AddRoleAPI(this.form);
        this.getRole();
        this.closeDialog();
        // console.log(form);
      });
      // this.closeDialog()
    },
    //每页变化
    handleSizeChange(val) {
      this.query.pagesize = val;
      this.getRole();
    },
    //处理页面优化
    handleCurrentChange(val) {
      //把选择的页面同步到query中
      this.query.page = val;
      this.getRole();
    },
    // 自定义下标
    indexMethod(index) {
      return index + 1 + this.query.pagesize * (this.query.page - 1);
    },
    //删除角色
    async handleDel(roleId) {
      try {
        //询问
        await this.$confirm("此操作不可逆哦，确定要做掉他吗", "温馨提示", {
          type: "warning",
        });
        //确定了
        if (this.query.page > 1 && this.form === 1) {
          this.query.page--;
        }
        //发请求
        await delRoleAPI(roleId);
        //成功提示
        this.$message.success("干掉了");
        //重新获取列表
        this.getRole();
      } catch (err) {
        //取消
      }
    },
    // 打开编辑弹窗
    async handleOpenEditDialog(roleId) {
      this.showEditDialog = true;
      // 根据id做回显
      const resp = await getRoleDetailAPI(roleId);
      this.form = resp.data;
    },
    // 关闭编辑弹窗
    handleEditClose() {
      this.showEditDialog = false;
    },
    //编辑角色
    async handleEdit() {
      // 发起编辑请求
      await editRoleAPI(this.form);
      // 关闭弹窗
      this.handleEditClose();
      this.getRole();
    },
    //分配权限弹窗关闭
    handleAssignClose() {
      this.showAssignDialog = false;
      //清空tree组件的选中状态
      this.$refs.treeRef.setCheckedKeys([]);
    },
    // 打开弹窗
    async handleOpenAssignDialog(rowId) {
      //保存角色id
      this.rowId = rowId;
      // 显示弹窗
      this.showAssignDialog = true;
      // 请求列表\
      const resp = await getPermListAPI();
      console.log(resp);
      // 转为树形列表在赋值
      this.permTreeData = list2Tree(resp.data, "0");
      // 回显
      const resp2 = await getRoleDetailAPI(rowId);
      // 把后台返回的权限id的数组作为参数传给setCheckedKeys（）
      this.$refs.treeRef.setCheckedKeys(resp2.data.permIds);
    },
    //分配权限
    async handleAssign() {
      // 获取属性组件选中的节点（给当前角色分配的权限）
      const permIds = this.$refs.treeRef.getCheckedKeys();
      // 发起请求
      await assignPermAPI(this.rowId, permIds);

      // 关闭
      this.handleAssignClose();
      // 提示
      this.$message.success("cehggong");
    },
  },
};
</script>

<style>
.el-pagination {
  margin-top: 20px;
}
</style>